/**
 * iframe 包装器. 用于查看url.
 */
var PreviewFrame = (function(){  
    
    var previewFrameTmp = [
        '<div class="dashboard mainContentPane">',
            '<div class="chatViewerHeader">',
                '<div class="chatViewerHeaderLeft left">',
                    '<h2 class="chatViewerTitle"><%=o.title%></h2>',
                '</div>',
                '<div class="chatViewerHeaderRight toolbar disperse"></div>',
            '</div>',            
            '<iframe class="previewFrame" style="height: calc(100% - 37px);width: 100%;border: none;"></iframe>',
            '<div class="chatPanelParticipantsWrapper">',
                '<div class="chatPanelParticipantsList"></div>',
                '<div class="participantAdderWrapper">',
                    '<div class="chatMemberViewHeader">',
                        '<span class="closeAddChatMemberViewBtn" title="Back"></span>',
                        lan('app.im.participant.addTip'),                      
                    '</div>',
                    '<div class="chatMemberAddList"></div>',            
                '</div>',
            '</div>',
        '</div>'
    ].join('');
      
    function _PreviewFrame(data){
        this.data = data;
    }
    _PreviewFrame.prototype.init = function(){
        var _this = this;
        if(this.$container){
            if(!this.isInited){
                this.$wrapper = $(tmpl(this.data, previewFrameTmp)).appendTo(this.$container);
                this.$participantListWrapper = this.$wrapper.find('.chatPanelParticipantsWrapper'); 
                this.$participantAdderWrapper = this.$wrapper.find('.participantAdderWrapper');
                
                this.$chatMemberView = this.$participantListWrapper.find('.chatPanelParticipantsList');
                //hide member view.   
                this.$chatMemberView.delegate('.closeChatMemberViewBtn', 'click', function(){
                    _this.hideParticipants();
                });  
                
                _this.$chatMemberView.delegate('.adminSIcon', 'click', function(){
                    if(!_this.data.perm.adm){                        
                        return false;
                    }                    
                    var $self = $(this),
                        tip,
                        tipFun;
                        userName = $self.parent().find('.chatMemberName').text();
                        
                    function getAdmin(){
                        return _this.$participantListWrapper.find('.adminSIcon.creator, .adminSIcon.admin').map(function(){
                            return $(this).attr('uid');    
                        }).get();    
                    }
                        
                    function saveAdmin(){                        
                        var data = {
                            type : _this.data['relType'],
                            auids : getAdmin()
                        };   
                        page.biz.uploadURLEntity(_this.data['id'], Object.toFormData({
                            url : JSON.stringify(data)
                        }), function(msg){});     
                    }
                    if($self.hasClass('admin')){
                        tip = 'Do you want to remove group {0}\'s admin role?'.format(userName);  
                        tipFun = function(){               
                            $self.removeClass('admin').addClass('user').attr('src', '/ujs/images/common16/user2.png');
                            $self.parent().find('.closeBtn').attr('style', '');
                        };  
                    } else {
                        if($self.hasClass('user')){
                            if(getAdmin().length > 9){
                                bubble.msg('Admins cannot be more than ten');
                                return false;
                            }
                            tip = 'Do you want to set {0} as admin'.format(userName);
                            tipFun = function(){                                
                                $self.removeClass('user').addClass('admin').attr('src', '/ujs/images/common16/user3.png');
                                $self.parent().find('.closeBtn').attr('style', 'display:none;');
                            };
                        };
                    }
                    if(tip && tipFun){
                        bubble.confirm(tip, function(){
                            tipFun();
                            saveAdmin();    
                        });     
                    }               
                    return false;
                }); 
                       
               _this.$chatMemberView.delegate('.closeBtn', 'click', function(){
                    var $chatMemberItem = $(this).closest('.chatMember');
                    
                    var memberID = $chatMemberItem.attr('id'),
                        memberType = $chatMemberItem.attr('type');
                    var doneDelete = ujs.hr(function(msg){
                        $chatMemberItem.animate({
                            scale : 0.1
                        }, 500, function() {
                            $(this).remove();
                        });                          
                    });
                    bubble.confirm(lan('app.im.participant.delTip'), function(){
                        var deleteData = {
                            type : _this.data['relType']
                        };
                        
                        if(memberType == MemberType.GROUP){
                            deleteData['rug'] = [memberID];
                        } else {
                            deleteData['ru'] = [memberID];
                        }
                         
                        page.biz.uploadURLEntity(
                            _this.data['id'],
                            Object.toFormData({
                                url : JSON.stringify(deleteData)
                            }), 
                            doneDelete
                        );                            
                    }); 
                    return false;                                     
                });
                                        
                if(_this.data.perm.adm){                        
                    _this.$chatMemberView.addClass('administrator');
                }
        
                //adder
                _this.$chatMemberView.delegate('.chatMemberAdder', 'click', function(){                    
                    _this.$participantAdderWrapper.slideDown();
                                        
                    var $adder = $(ChatPanelView.participantAdder);
                    var $chatMemberAddList = _this.$participantAdderWrapper.find('.chatMemberAddList'); 
                    $chatMemberAddList.html('');
                    $adder.appendTo($chatMemberAddList);
                    _this.memberSelector = new MemberSelector($adder.find('.memberSelector3'), {
                        width : 595,
                        height : 120,
                        treeType : 'adminchat',
                        mode : 'expand',
                        clickable : false                        
                    });
                    //hide add member view.
                    _this.$participantListWrapper.delegate('.closeAddChatMemberViewBtn', 'click', function(){
                        _this.$participantAdderWrapper.slideUp();
                    });
                    
                    //add participant.
                    $adder.delegate('.saveChatMemberViewBtn', 'click', function(){                        
                        var members = _this.memberSelector.getUserAndGroup();    
                        if(members['groups'].length || members['users'].length){                    
                            page.biz.uploadURLEntity(
                                _this.data['id'],
                                Object.toFormData({
                                    url : JSON.stringify({
                                        type : _this.data['relType'],
                                        aug : members['groups'],
                                        au : members['users']
                                    })
                                }), 
                                function(msg){                            
                                    _this.loadParticipants();  
                                    _this.$participantAdderWrapper.slideUp();   
                                    _this.hideParticipants();           
                                }
                            );   
                        } else {
                            bubble.msg(lan('app.im.participant.selectTip'));
                        } 
                        return false;
                    });
                });
                //--------------------------------------------------------------------
                this.$iframe = this.$wrapper.find('iframe');
                this.$iframe.load(function(){
                    ujs.ui.paneMask.hide(_this.$wrapper);
                });
                this.to(this.data['src']);
                //----------------------------------------------------------------------------
                
                this.toolbar = this.$wrapper.find('.chatViewerHeaderRight').toolbar({
                    cls : 'disperse'
                }).data('toolbar');
                
                //关闭.
                this.toolbar.addImageButton({
                    id : 'closeDialog',
                    image : ujs.getRes('images/common24/minimize.png'),
                    cls : 'icon imageBtn',
                    tooltip : 'Close',
                    onClick : function() {
                        page.contentCardLayout.showItem('dashboard');                        
                    }
                });

                if(true || _this.data['perm'] && _this.data['perm']['vpar']){                     
                    this.toolbar.addImageButton({
                        id : 'shows',
                        image : ujs.getRes('images/common24/user_group.png'),
                        cls : 'icon imageBtn',
                        tooltip : 'Show Participants',
                        onClick : function() {                             
                            _this.showParticipants();       
                        }
                    });
                }
                
                if(_this.data['perm'] && _this.data['perm']['vpar']){                     }else {
                    this.toolbar.hideItem('shows');
                }
                
                if(true || _this.data['perm'] && _this.data['perm']['svy']){                    
                    //打开报表窗口                    
                    this.toolbar.addImageButton({
                        id : 'report',
                        image : ujs.getRes('images/common24/report.png'),
                        cls : 'icon imageBtn',
                        tooltip : 'Report',
                        onClick : function() {                             
                            var obj = page.urlStore.getItem(_this.data['id']);
                            ujs.ui.Dialog.get({   
                                icon : ujs.getRes('images/common32/report.png'),    
                                title : obj['name'],
                                url : obj['url'].replace('mobile', 'report'),
                                width : 800,
                                height : 600                        
                            });               
                        }
                    });
                }
                                if(_this.data['perm'] && _this.data['perm']['svy']){                    
                                }else {
                                    
                                    this.toolbar.hideItem('report');        
                                }
                //在新窗口中打开
                this.toolbar.addImageButton({
                    id : 'openInNewWin',
                    image : ujs.getRes('images/common24/new_win.png'),
                    cls : 'icon imageBtn',
                    tooltip : 'Open in new window',
                    onClick : function() {
                        window.open(_this.data['src']);                        
                    }
                });    
                
                //刷新
                this.toolbar.addImageButton({
                    id : 'refresh',
                    image : ujs.getRes('images/common24/refresh.png'),
                    cls : 'icon imageBtn',
                    tooltip : 'Refresh',
                    onClick : function() {
                        _this.refresh();                        
                    }
                });
                
                //更新
                if((_this.data['perm'] && (_this.data['perm']['upd'] || _this.data['perm']['adm']))) {
                    this.toolbar.addImageButton({
                        id : 'edit',
                        image : ujs.getRes('images/common24/edit.png'),
                        cls : 'icon imageBtn',
                        tooltip : 'Edit',
                        onClick : function() {   
                            
                            var en = page.urlStore.getItem(_this.data['id']);
                                                     
                            ujs.ui.Dialog.get(EditPageDialog, {
                                title : 'Edit ' + {
                                        survey : 'Survey',
                                        eventurl : 'Event',
                                        web : 'Link',
                                        page : 'Webpage'
                                    }[_this.data['relType']],
                                relType : _this.data['relType'],
                                ueid : _this.data['id'],
                                publish : !!en['launchTime'],
                                onEditPage : function(){
                                    ujs.ui.Dialog.get(URLDialog, {       
                                        title : 'Edit',             
                                        mode : 'edit',
                                        relType : _this.data['relType'],
                                        ueid : _this.data['id']                        
                                    });     
                                }
                            });                                                       
                        }
                    });    
                }                            
                this.isInited = true;  
            }
        }
    };
    
    /**
     * 刷新. 
     */
    _PreviewFrame.prototype.refresh = function(){
        if(this.$iframe){ 
            var oldUrl = this.getUrl();            
            this.to(null, true);           
        }
    };
    
    /**
     * 跳转到指定的页.
     * @param {String} url
     * @param {Boolean} isForceRefresh  是否强制刷新，即使url与当前url相同.
     */
    _PreviewFrame.prototype.to = function(url, isForceRefresh){   
        var oldUrl = this.getUrl();
        if(!url){
            url = oldUrl;
        }
        if(oldUrl == url){
            if(isForceRefresh === true){
                url = url.addQuery({
                    t : Date.now()
                });
            } else {
                return this;
            }
        }
        ujs.ui.paneMask.show(this.$wrapper, 'load');
        if(this.$iframe){            
            this.$iframe.attr('src', url);            
        }
    };
    
    _PreviewFrame.prototype.getUrl = function(){
        return this.$iframe ? this.$iframe.attr('src') : '';
    };
    
    _PreviewFrame.prototype.loadParticipants = function(cb){
        var _this = this,
            teid = _this.data['id'];        
        //参与者数据.
        var participantPromise = $.get('/apis/url/{0}'.format(teid));        
        var handler = function(msg){                        
            var users = msg['ue']['participants'];            
            users.sort(function(a, b){
                return parseInt(a.type) <= parseInt(b.type);
            });       
            _this.parts = users;            
            _this.$chatMemberView.html(tmpl(ChatPanelView.participantList, {
                participants : users
            }));
            _this.$chatMemberView.find('#' + _this.data['id']).find('.chatMemberName').text(_this.data['name']);
            cb && cb(msg);
            
            
            //                 
                if(_this.data.perm.par != 1){
                     _this.$chatMemberView.find('.chatMemberAdder').remove();
                 }
                        
            
            _this.$chatMemberView.find('.p_search').searchable({
                placeholder : 'Search ...',
                isShowSearchBtn : false,
                style : 'margin-right: 10px;margin-top: 3px;',
                boxStyle : 'zoom: 0.8;width:120px;',
                onKeyup : function(val){                    
                    _this.$chatMemberView.find('.chatMember').filterByText(val, '.chatMemberName');
                },
                //搜索提交时.
                onSearch : function(val, searchType, $searchBox) {},
                //取销搜索时.
                onCancelSearch : function($searchBox) {                    
                    _this.$chatMemberView.find('.chatMember').filterByText('', '.chatMemberName');
                }
            });
        };
        
        $.when(participantPromise).done(function(msg, status, xhr){
            handler(msg);
        });
    };
            
    _PreviewFrame.prototype.showParticipants = function(){    
        var _this = this;    
        _this.loadParticipants(function(msg){
            _this.$participantListWrapper.slideDown();
        });    
    };
    
    _PreviewFrame.prototype.hideParticipants = function(){
        if(this.$participantListWrapper){
            this.$participantListWrapper.slideUp();
        }
    };
    
    
    return _PreviewFrame;    
})();